from PIL import Image, ImageFont, ImageDraw
 
def text_to_led_matrix(text, font_path, font_size, width, height, bg_color=(0, 0, 0), fg_color=(128, 0, 0), padding=2):
    """
    将文字转换成LED矩阵图像
    :param text: 要转换的文字
    :param font_path: 字体文件路径
    :param font_size: 字体大小
    :param width: LED矩阵的宽度
    :param height: LED矩阵的高度
    :param bg_color: 背景颜色
    :param fg_color: 前景颜色
    :param padding: 文字和矩阵边缘的间距
    :return: PIL Image对象
    """
    char_width = font_size
    char_height = font_size
    matrix_width = (width // char_width) * char_width
    matrix_height = (height // char_height) * char_height
    
    # 创建一个新的黑色背景图像
    image = Image.new('RGB', (matrix_width, matrix_height), color=bg_color)
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype(font=font_path, size=font_size)
    
    # 计算文字应该绘制的起始位置
    x = (matrix_width - len(text) * (char_width + padding) + padding) // 2
    y = (matrix_height - char_height + padding) // 2
    
    # 绘制文字
    for i, char in enumerate(text):
        draw.text((x + i * (char_width + padding), y), char, font=font, fill=fg_color)
    
    return image
 
# 使用示例
if __name__ == '__main__':
    text = "Python"
    font_path = "/Users/aiqikeji/Documents/ttfs/OPPOSans-B.ttf"  # 确保字体文件存在于此路径
    font_size = 40
    width = 300
    height = 100
    image = text_to_led_matrix(text, font_path=font_path, font_size=font_size, width=width, height=height)
    image.show()  # 显示图像
    # image.save('led_matrix.png')  # 保存图像文件
